<?php
/**
* @software         [JiJinCMS]
* @author           [上海集锦信息科技有限公司]
* @website          [http://www.jijinweb.com]
* @email            [sunny@jijinweb.com]
**/
namespace app\admin\model;
use think\Model;
use think\facade\Db;
class ModelModel extends Model{
    const modelTempPath = 'data/modelTemp/'; //模型表单模板路径    
    const modelTempMemberPath = 'data/modelTempMember/'; //会员模型表单模板路径
    const modelCachePath='data/cache/modelCache.php';//模型缓存文件
    protected $name = 'model';
    protected $pk = 'modelid';
    //把数组转换为字符串便于存到数据里
    public function arr2string($arr){
        $str=  $arr?implode(",", $arr):"";
        if($str){
            $str=",".$str.",";
        }
        return $str;
    }    
    //自动完成-get_formtemp
    public function get_formtemp($data) {
        $field_name=$data['field_name'];
        $field=$data['field'];
        $str="";
        foreach($field as $key=>$v){
            $str.=$field_name[$key]."<!--field-->".$field[$key]."\r\n";
        }        
        return trim($str);
    }  
    //自动完成-获取表名
    public function get_table_name($data){
        return Db::name("table")->where("table_id",$data['table_id'])->value("table_name");
    }    
    /**
     * 更新模型模板文件
     * @param type $modelId 模型id
     * @return boolean
     */
    public function updateModelTemp($model){
        //将model里的is_enter is_contribute must_enter is_list is_search is_sort 依次拿出来和table_field对比，如果不存在就删除（防止因删除字段和修改字段名而造成model里的这些字段不更新导致的错误）
        $field=Db::name("table_field")->field("field")->order("sort asc,field_id asc")->where("table_id",$model['table_id'])->select();        
        $new=array("modelid"=>$model['modelid'],"is_enter"=>"","is_contribute"=>"","must_enter"=>"","is_list"=>"","is_search"=>"","is_sort"=>"");
        foreach($field as $v){
            //录入项
            if(strstr($model['is_enter'], ",".$v["field"].",")){
                $new["is_enter"].=",".$v["field"];
            }            
            //投稿
            if(strstr($model['is_contribute'], ",".$v["field"].",")){
                $new["is_contribute"].=",".$v["field"];
            }
            //必填项
            if(strstr($model['must_enter'], ",".$v["field"].",")){
                $new["must_enter"].=",".$v["field"];
            }
            //列表展示
            if(strstr($model['is_list'], ",".$v["field"].",")){
                $new["is_list"].=",".$v["field"];
            }    
            //搜索项
            if(strstr($model['is_search'], ",".$v["field"].",")){
                $new["is_search"].=",".$v["field"];
            }    
            //排序项
            if(strstr($model['is_sort'], ",".$v["field"].",")){
                $new["is_sort"].=",".$v["field"];
            }             
        }
        $new["is_enter"]=isset($new["is_enter"])?$new["is_enter"].",":"";
        $new["is_contribute"]=isset($new["is_contribute"])?$new["is_contribute"].",":"";
        $new["must_enter"]=isset($new["must_enter"])?$new["must_enter"].",":"";
        $new["is_list"]=isset($new["is_list"])?$new["is_list"].",":"";
        $new["is_search"]=isset($new["is_search"])?$new["is_search"].",":"";
        $new["is_sort"]=isset($new["is_sort"])?$new["is_sort"].",":"";
        $this->update($new);
        //
        $formtemp=  explode("\r\n",$model['formtemp']);
        $modelTemp="";
        foreach($formtemp as $key=>$v){
            $f=explode("<!--field-->",$v);
            if(isset($f[1])){
                if(!strstr($new["is_enter"], ",".$f[1].",")){
                    continue;;
                }
                $field=Db::name("table_field")->where([["table_id","=",$model['table_id']],["field","=",$f[1]]])->find();
                if($field){
                    $htmlcode=$field["htmlcode"];
                    $htmlcode=  str_replace("{modelFieldTemp_name}", $f[0],$htmlcode);//名称替换
                    $modelTemp=$modelTemp."\r\n".$htmlcode;                
                }
            }
        }
        //替换标签
        $TemplateModel=new \app\admin\model\TemplateModel();
        $TemplateModel->content=$modelTemp;
        $TemplateModel->replaceTemplate();
        $modelTemp=$TemplateModel->content;
        //
        $modelTemp=htmlspecialchars_decode($modelTemp);
        file_put_contents(base_path().self::modelTempPath.$model['modelid'].".php",$modelTemp);
        return true;
    }

    /**
     * 更新模型模板文件（会员投稿表单）
     * @param type $modelId 模型id
     * @return boolean
     */
    public function updateModelTempMember($model){
        //将model里的is_enter is_contribute must_enter is_list is_search is_sort 依次拿出来和table_field对比，如果不存在就删除（防止因删除字段和修改字段名而造成model里的这些字段不更新导致的错误）
        $field=Db::name("table_field")->field("field")->order("sort asc,field_id asc")->where("table_id",$model['table_id'])->select();
        $new=array("modelid"=>$model['modelid'],"is_enter"=>"","is_contribute"=>"","must_enter"=>"","is_list"=>"","is_search"=>"","is_sort"=>"");
        foreach($field as $v){
            //录入项
            if(strstr($model['is_enter'], ",".$v["field"].",")){
                $new["is_enter"].=",".$v["field"];
            }            
            //投稿
            if(strstr($model['is_contribute'], ",".$v["field"].",")){
                $new["is_contribute"].=",".$v["field"];
            }
            //必填项
            if(strstr($model['must_enter'], ",".$v["field"].",")){
                $new["must_enter"].=",".$v["field"];
            }
            //列表展示
            if(strstr($model['is_list'], ",".$v["field"].",")){
                $new["is_list"].=",".$v["field"];
            }    
            //搜索项
            if(strstr($model['is_search'], ",".$v["field"].",")){
                $new["is_search"].=",".$v["field"];
            }    
            //排序项
            if(strstr($model['is_sort'], ",".$v["field"].",")){
                $new["is_sort"].=",".$v["field"];
            }             
        }
        $new["is_enter"]=isset($new["is_enter"])?$new["is_enter"].",":"";
        $new["is_contribute"]=isset($new["is_contribute"])?$new["is_contribute"].",":"";
        $new["must_enter"]=isset($new["must_enter"])?$new["must_enter"].",":"";
        $new["is_list"]=isset($new["is_list"])?$new["is_list"].",":"";
        $new["is_search"]=isset($new["is_search"])?$new["is_search"].",":"";
        $new["is_sort"]=isset($new["is_sort"])?$new["is_sort"].",":"";
        $this->update($new);
        //
        $formtemp=  explode("\r\n",$model['formtemp']);
        $modelTemp="";
        foreach($formtemp as $key=>$v){
            $f=explode("<!--field-->",$v);
            if(isset($f[1])){
                if(!strstr($new["is_contribute"], ",".$f[1].",")){
                    continue;;
                }
                $field=Db::name("table_field")->where([["table_id","=",$model['table_id']],["field","=",$f[1]]])->find();
                if($field){
                    $htmlcode=$field["memberhtmlcode"];
                    $htmlcode=  str_replace("{modelFieldTemp_name}", $f[0],$htmlcode);//名称替换
                    $modelTemp=$modelTemp."\r\n".$htmlcode;                
                }
            }
        }
        $modelTemp=htmlspecialchars_decode($modelTemp);
        file_put_contents(base_path().self::modelTempMemberPath.$model['modelid'].".php",$modelTemp);
        return true;
    }  
    /**
     * 更新栏目模型模板文件
     * @param type $modelId 模型id
     * @return boolean
     */
    public function updateCatModelTemp($model){
        //将model里的is_enter  must_enter 依次拿出来和cat_field对比，如果不存在就删除（防止因删除字段和修改字段名而造成model里的这些字段不更新导致的错误）
        $field=Db::name("cat_field")->field("field")->order("sort asc,field_id asc")->select();
        $new=array("modelid"=>$model['modelid'],"cat_is_enter"=>"","cat_must_enter"=>"");
        foreach($field as $v){
            //录入项
            if(strstr($model['cat_is_enter'], ",".$v["field"].",")){
                $new["cat_is_enter"].=",".$v["field"];
            }            
            //必填项
            if(strstr($model['cat_must_enter'], ",".$v["field"].",")){
                $new["cat_must_enter"].=",".$v["field"];
            }             
        }
        $new["cat_is_enter"]=isset($new["cat_is_enter"])?$new["cat_is_enter"].",":"";
        $new["cat_must_enter"]=isset($new["cat_must_enter"])?$new["cat_must_enter"].",":"";
        $this->update($new);
        //
        $formtemp=  explode("\r\n",$model['cat_formtemp']);
        $modelTemp="";
        foreach($formtemp as $key=>$v){
            $f=explode("<!--field-->",$v);
            if(isset($f[1])){
                if(!strstr($new["cat_is_enter"], ",".$f[1].",")){
                    continue;
                }
                $field=Db::name("cat_field")->where("field",$f[1])->find();
                if($field){
                    $htmlcode=$field["htmlcode"];
                    $htmlcode=  str_replace("{modelFieldTemp_name}", $f[0],$htmlcode);//名称替换
                    $modelTemp=$modelTemp."\r\n".$htmlcode;                
                }
            }
        }
        $modelTemp=htmlspecialchars_decode($modelTemp);
        file_put_contents(base_path().self::modelTempPath.$model['modelid']."_cat.php",$modelTemp);
        return true;
    }    
    //更新模型缓存
    public function updateCache(){
        $cat=$this->field("modelid,table_id,formtemp,table_name,status,name,sort,contribute,autochecked,is_enter,is_contribute,must_enter,is_list,is_search,is_sort,cat_is_enter,cat_must_enter")->select()->toArray();
        $newcat=array();
        foreach($cat as $v){
            $newcat[$v["modelid"]]=$v;
        }
        $arr_str=var_export ($newcat,true);
        $arr_str="<?php \r\n \$GLOBALS['model']=".$arr_str.";";     
        file_put_contents(base_path().self::modelCachePath,$arr_str);
    } 
    //删除表单缓存文件
    public function deleteTemp($modelid){
        @unlink(base_path().self::modelTempPath.$modelid.".php");        
        @unlink(base_path().self::modelTempMemberPath.$modelid.".php");  
        @unlink(base_path().self::modelTempPath.$modelid."_cat.php");  
    }
    //
    //获取批量导入excel模板，用于用户在后台批量导入数据的
    public function GetImportExcelDemo($data){
        $model=$this->find($data['modelid']);
        $formtemp=  explode("\r\n",$model["formtemp"]);
        $data["import_field"]=explode(",",$data["import_field"]);
        foreach($formtemp as $key=>$v){
            $f=explode("<!--field-->",$v);
            if(!in_array($f[1],$data["import_field"])){
                continue;
            }      
            if(!$f[1]){
                continue;
            }               
            $FieldData[]=$f[0]."==".$f[1];
        }
        $objReader = \PHPExcel_IOFactory::createReader('Excel5');
        $objPHPExcel = $objReader->load(base_path()."data/ImportExcelDemo/import_template.xls");
        $sheet=$objPHPExcel->setActiveSheetIndex(0);
        //设置第一列为栏目字段
        if($data['cat_type']=="catName"){
            $sheet ->setCellValue("A1","栏目名称==catid");
            $sheet->getColumnDimension("A")->setAutoSize(true);
        }elseif($data['cat_type']=="catid"){
            $sheet ->setCellValue("A1","栏目ID==catid");
            $sheet->getColumnDimension("A")->setAutoSize(true);
        }else{
            
        } 
        //
        foreach($FieldData as $key=>$v){
            if($data['cat_type']!="selfCheck"){
                $key2=$key+1;
            }else{
                $key2=$key;
            }
            $no=IntToChr($key2);
            $sheet ->setCellValue($no."1",$v);
            $sheet->getColumnDimension($no)->setAutoSize(true);
        }    
        //echo $data['cat_type'];exit;
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$model["name"].'-数据导入结构-'.date("Y-m-d His").'.xls"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');        
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');       
    }    
}
